<?php
require_once "Base64.class.php";
/**
 *
 * 反向代理Cookie
 *
 */
class CookieDecoder {

	private $cookie;
	public function __construct($request_url) {
		$parsed_url = parse_url($request_url);
		if (!array_key_exists('path',$parsed_url)) {
			$parsed_url['path'] = '\\';
		}
		foreach($_COOKIE as $enc_cookie_key => $enc_cookie_val) {
			$encookie_key = explode(",",Base64::decode($enc_cookie_key));
		    if (count($encookie_key) == 3) { // 这是我们期待的格式，代表解析成功，否则为正常的cookie
		        	if ($this->isDomainMatch($encookie_key[0],$parsed_url["host"]) && $this->isPathMatch($encookie_key[1],$parsed_url["path"])) { //应发送此Cookie
		        		$this->cookie[] = Base64::decode($enc_cookie_val);
		        	}
			}
		}
	}

	private function isDomainMatch($cookie_domain, $request_host) {
		$cookie_domain = preg_replace("/^[^\w]+/","",$cookie_domain);//去掉非正常字符 如.test.com替换为test.com
		return is_int(strpos($request_host,$cookie_domain));
	}

	private function isPathMatch($cookie_path, $request_path) {
		$cookie_path = str_replace("\\","/",$cookie_path);// 替换反斜杠为正斜杠
		return strpos($request_path,$cookie_path) == 0;
	}

	public function getCookie() {
		if (!empty($this->cookie)) {
		    return "Cookie: ".implode("; ",$this->cookie);
		}
		return "";
	}
}
